<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select
                            v-model="instruction.fundAccountCode"
                            size="mini"
                            @change="handleChange(instruction.fundAccountCode, 'fundAccountCode')"
                        >
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码:" v-if="isBatchFund">
                        <el-select
                            v-model="instruction.stockCode"
                            @change="handleChange(instruction.stockCode, 'stockCode')"
                            filterable
                            @visible-change="handleStockVisibleChange"
                            :filter-method="getstockCodeList"
                            :loading="selectLoading"
                            size="mini"
                            clearable
                            @clear="getstockCodeList('')"
                        >
                            <el-option
                                v-for="i in stockCodeSelectData"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockNameSt"
                                :value="i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select v-model="instruction.businClass" size="mini" @change="handleChange(instruction.businClass, 'businClass')">
                            <el-option v-for="i in businessSelectData" :key="i.value" :label="i.label" :value="i.value"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:" v-if="isBatchFund">
                        <el-select
                            v-model="instruction.orderDirection"
                            size="mini"
                            @change="handleChange(instruction.orderDirection, 'orderDirection')"
                            :class="['font-color-' + textColor]"
                        >
                            <el-option
                                v-for="i in orderDirectionSelectData"
                                :key="i.dictKey"
                                :label="i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleTextColor(i.dictKey)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="委托方向:" v-if="isBatchStock">
                        <el-select
                            v-model="instruction.orderDirection"
                            size="mini"
                            @change="handleChange(instruction.orderDirection, 'orderDirection')"
                            :class="['font-color-' + textColor]"
                        >
                            <el-option
                                v-for="i in orderDirectionSelectData"
                                :key="i.dictKey"
                                :label="i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleTextColor(i.dictKey)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="指令数量:">
                        <RiskInputNumber
                            :input="instruction.orderAmount"
                            :inputAfter="'份'"
                            :colorStyle="textColor"
                            :maxlength="9"
                            :field="'orderAmount'"
                            :precision="2"
                            :disabled="orderAmountStatus"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="指令金额:">
                        <RiskInputNumber
                            :input="instruction.orderBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderBalance'"
                            :disabled="orderBalanceStatus"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import { getBusinessType } from '@/pages/risk-time/api';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { handleTextColor, highlightColor } from '@/utils/tools';

@Component({
    name: 'CwOpenFundForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 场外基金指令
export default class CwOpenFundForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    stockInfoCache: any;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多证券指令

    Invest: any = new Invest();
    handleTextColor = handleTextColor;
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    allStockType: any[] = [];
    allOrderDirection: any[] = [];
    orderDirectionSelectData: any[] = [
        {
            dictKey: 'D',
            dictKeyName: '基金认购',
        },
        {
            dictKey: 'p',
            dictKeyName: '开基申购',
        },
        {
            dictKey: 'q',
            dictKeyName: '开基赎回',
        },
        // {
        //     dictKey: 'E',
        //     dictKeyName: '基金转换',
        // },
    ];
    businessSelectData: SelectOptionItemData[] = [];
    defaultBusinessTypeData: SelectOptionItemData[] = [
        {
            label: '开放式基金',
            value: 'A',
        },
    ];
    investPriceSelectData: any[] = []; // 价格模式下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    orderAmountStatus: boolean = false;
    orderBalanceStatus: boolean = false;

    private instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        marketCode: '',
        orderDirection: '', // 委托方向
        stockCode: '', // 证券代码
        businClass: 'A',
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        fundNameSt: '',
        fundAccountName: '',
    };
    stockInfo: any = {};
    textColor: string = ''; // 表单项字体颜色

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取价格模式下拉框数据
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);

        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        this.businessSelectData = this.defaultBusinessTypeData;
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction.orderDirection', { immediate: true, deep: true })
    handleFieldColor() {
        if (['D', 'p'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[1];
        } else if (this.instruction.orderDirection === 'q') {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    @Watch('stockInfoCache', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.stockInfoCache) {
            this.stockInfo = this.stockInfoCache;
            this.getstockCodeList(this.stockInfo.stockCode);
        }
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (this.detail && this.detail.instruction) {
            this.instruction.fundAccountCode = this.detail.instruction.fundAccountCode;
        } else {
            if (newData && newData.length) {
                this.instruction.fundAccountCode = newData[0].fundAccountCode;
            }
        }
    }

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            if (instruction.orderDirection === 'D' || instruction.orderDirection === 'p') {
                // 基金认购,开基申购
                this.detail.orderAmount = '';
                this.orderAmountStatus = true;
                this.orderBalanceStatus = false;
            } else if (instruction.orderDirection === 'q') {
                // 开基赎回
                this.detail.orderBalance = '';
                this.orderAmountStatus = false;
                this.orderBalanceStatus = true;
            } else {
                this.orderAmountStatus = false;
                this.orderBalanceStatus = false;
            }
            await this.getstockCodeList(instruction.stockCode);
            // this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === instruction.stockCode);
            // if (this.stockInfo && this.stockInfo.marketCode && this.stockInfo.stockType) {
            //     this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, false);
            // }
            this.instruction = JSON.parse(JSON.stringify(instruction));
            this.instruction.businClass = instruction.businessType;
        }
    }

    @Watch('detail', { immediate: true, deep: true })
    async setForm() {
        if (this.detail && this.detail.fundCode) {
            let instruction = this.detail;
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });
            if (instruction.orderDirection === 'D' || instruction.orderDirection === 'p') {
                // 基金认购,开基申购
                this.detail.orderAmount = '';
                this.orderAmountStatus = true;
                this.orderBalanceStatus = false;
            } else if (instruction.orderDirection === 'q') {
                // 开基赎回
                this.detail.orderBalance = '';
                this.orderAmountStatus = false;
                this.orderBalanceStatus = true;
            } else {
                this.orderAmountStatus = false;
                this.orderBalanceStatus = false;
            }
            for (const key in instruction) {
                this.instruction[key] = instruction[key];
            }
            // 指令修改回显
            if (this.detail.instNo) {
                // 组合编码
                this.instruction.fundAccountCode = this.detail.groupCode;
                // 组合名称
                this.instruction.fundAccountName = this.detail.groupName;
            }
            await this.getstockCodeList(this.detail.stockCode);
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === this.detail.stockCode);
            this.instruction.reportCode = this.stockInfo?.reportCode;
            this.instruction.marketCode = this.stockInfo?.marketCode;
            // this.$emit('getStockInfo', this.stockInfo, '8');
            // if (this.stockInfo.marketCode && this.stockInfo.stockType) {
            //     this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, false);
            // }

            this.instruction.fundCode = this.detail.fundCode;
            this.instruction.fundAccountCode = this.detail.fundAccountCode;
            this.instruction.stockCode = this.detail.stockCode;
            this.instruction.businClass = this.detail.businClass;
            this.instruction.orderAmount = this.detail.orderAmount;
        }
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instruction.fundCode];
    }

    // 参数变动
    handleChange(value, field) {
        if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'fundAccountCode') {
            this.handleFundAccountCodeChange(value);
        } else if (field === 'stockCode') {
            this.handleStockCode(value);
        } else if (field === 'orderDirection') {
            this.handleOrderDirectionChange(value);
        }
        this.$emit('handleSettingValue', this.instruction, '8');
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        this.$emit('handleSettingValue', this.instruction, '8');
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        // this.handleFundCodeChange(val);
        this.handleChange(val, 'fundCode');
    }

    handleFundCodeChange(val: string): void {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleStockCode(stockCode: string): void {
        this.instruction.orderDirection = '';

        if (stockCode) {
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === stockCode);
            this.instruction.reportCode = this.stockInfo.reportCode;
            this.instruction.marketCode = this.stockInfo.marketCode;
            this.$emit('getStockInfo', this.stockInfo);
        } else {
            this.instruction.reportCode = '';
            this.instruction.marketCode = '';
        }
        this.handleOrderDirectionChange(this.instruction.orderDirection);
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList(this.instruction.stockCode);
        }
    }

    // async handleStockBusinessType(marketCode, stockType, reset) {
    //     let res = await getBusinessType(marketCode, stockType);
    //     if (res && res.length > 0) {
    //         this.businessSelectData = res.map(
    //             (item) =>
    //                 ({
    //                     label: item.dictKeyName,
    //                     value: item.dictKey,
    //                 } as SelectOptionItemData)
    //         );

    //         let innerOrderDirectionData = res;
    //         innerOrderDirectionData.filter((ele) => {
    //             if (ele.dictKey == this.instruction.businClass) {
    //                 if (ele['innerDictionary'] && JSON.stringify(ele['innerDictionary']) !== '{}') {
    //                     this.orderDirectionSelectData = JSON.parse(ele['innerDictionary'] || '[]');
    //                     // 暂时隐藏基金转换 后续需要支持再放开
    //                     // this.orderDirectionSelectData = this.orderDirectionSelectData.filter((ele) => ele.dictKey !== 'E');
    //                 } else {
    //                     this.orderDirectionSelectData = [];
    //                     this.instruction.orderDirection = '';
    //                 }
    //                 if (this.orderDirectionSelectData.length && reset) {
    //                     this.instruction.orderDirection = this.orderDirectionSelectData[0].dictKey;
    //                 } else {
    //                     if (reset) {
    //                         this.yh_message_warn('该业务类型无对应的委托方向');
    //                     }
    //                 }
    //                 this.handleOrderDirectionChange(this.instruction.orderDirection);
    //             }
    //         });
    //     } else {
    //         this.businessSelectData = this.defaultBusinessTypeData;
    //     }
    // }

    // 获取证券代码下拉框数据
    async getstockCodeList(val: string | undefined) {
        this.selectLoading = true;
        await this.$axios
            .post('/dict/stock/report/select/5', {
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }

    handleOrderDirectionChange(value: string): void {
        if (value == 'D' || value == 'p') {
            // 基金认购,开基申购
            this.instruction.orderAmount = '';
            this.orderAmountStatus = true;
            this.orderBalanceStatus = false;
        } else if (value == 'q') {
            // 开基赎回
            this.instruction.orderBalance = '';
            this.orderAmountStatus = false;
            this.orderBalanceStatus = true;
        } else {
            this.orderAmountStatus = false;
            this.orderBalanceStatus = false;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';

.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
        .font-color-red {
            /deep/ input {
                color: red !important;
            }
            /deep/ .el-input-group__append {
                color: red !important;
            }
        }
        .font-color-green {
            /deep/ input {
                color: green !important;
            }
            /deep/ .el-input-group__append {
                color: green !important;
            }
        }
    }
}
</style>
